package com.net.http
{
	import com.net.Event.HttpEvent;
	
	import flash.events.EventDispatcher;
	import flash.net.Socket;
	import flash.utils.ByteArray;

	public class RequestStream extends EventDispatcher
	{
		private var socket:Socket;
		
		public function RequestStream(s:Socket)
		{
			socket=s;
		}
		
		/**
		 * 请求传来的数据到达
		 */
		internal function ByteArrive():void{
			dispatchEvent(new HttpEvent(HttpEvent.POST_ARRIVE));
		}
		
		/**
		 * 关闭流
		 */
		internal function close():void{
			if(socket.connected){
				socket.flush();
			}
		}
		
		
		//-----------------------------------------------------------------
		//                           写入数据
		//-----------------------------------------------------------------
		
		/**
		 * 传输响应的头
		 * 调用此方法后开始传输数据
		 * 当传输结束后需调用httprequest的close关闭对话
		 */
		public function writeReponseHeader(header:RequestHeader):void{
			if(socket.connected){
				socket.writeUTFBytes(header.getReponseHeader());
			}
		}
		
		/**
		 * 将数reponse数据主体写入
		 */
		public function writeReponseBytes(byte:ByteArray):void{
			if(socket.connected){
				socket.writeBytes(byte);
			}
		}
		
		
		//-----------------------------------------------------------------
		//                           读取数据
		//-----------------------------------------------------------------
		
		/**
		 * 读取一个字节
		 */
		public function readOneByte():int{
			return socket.readByte();
		}
		
		/**
		 * 已经传入的字节数
		 */
		public function get bytesAvailable():uint{
			return socket.bytesAvailable;
		}
		
		/**
		 * 读取一组字节
		 */
		public function readBytes(bytes:ByteArray,offset:uint=0,length:uint=0):void{
			return socket.readBytes(bytes,offset,length);
		}
		
		
		/**
		 * 读取一行字符串  
		 * 此方法将判定读取的长度  
		 * 如果长度超过指定长度则返回null
		 * 如果指定长度小于2 则不进行判定
		 * 以\r\n 结束的为一行
		 */
		public function readLine(maxLength:uint=0):String{
			if(maxLength<2){
				return readLineExpress();
			}
			var line:ByteArray=new ByteArray();
			var oneByte:int;
			var bytelength:int=0;
			while(bytelength<=maxLength){
				oneByte=socket.readByte();
				if(oneByte==13){
					oneByte=socket.readByte();
					if(oneByte==10){
						return line.toString();
					}
					//如果再次读取的不是10则将第一次读取到的13写入并在if结束后写入oneByte
					line.writeByte(13);
					bytelength++;
				}
				bytelength++;
				line.writeByte(oneByte);
			}
			return null;
		}
		
		/**
		 * 快速读取一行
		 */
		private function readLineExpress():String{
			var line:ByteArray=new ByteArray();
			var oneByte:int;
			while(true){
				oneByte=socket.readByte();
				if(oneByte==13){
					oneByte=socket.readByte();
					if(oneByte==10){
						return line.toString();
					}
					line.writeByte(13);
				}
				line.writeByte(oneByte);
			}
			return line.toString();
		}
	}
}